package com.guanzi.server.controller;


import com.guanzi.server.entity.Food;
import com.guanzi.server.entity.dto.FoodSaveDTO;
import com.guanzi.server.query.FoodOrderListQuery;
import com.guanzi.server.service.IFoodService;
import com.guanzi.server.util.RespBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author guanzi
 * @since 2021-06-04
 */
@RestController
@RequestMapping("/food")
public class FoodController {

    @Autowired
    private IFoodService foodService;

    /**
     * 点餐界面列表展示
     * @param foodOrderListQuery
     * @return
     */
    @PostMapping("/orderList")
    public RespBean getFoodList(FoodOrderListQuery foodOrderListQuery) {
        List<Food> foods = foodService.getFoodList(foodOrderListQuery);
        if (foods == null) {
            return RespBean.error("商家id为空或者异常错误！加载失败！");
        }
        return RespBean.success("加载成功！",foods);
    }

    /**
     * 已点列表展示
     * @return
     */
    @GetMapping("/foodListData")
    public RespBean getFoodListData() {
        List<Food> list = foodService.getFoodListData();
        return RespBean.success("加载成功！",list);
    }

    /**
     * 菜品保存
     *
     * 对应的dto => FoodSaveDTO
     * @param foodSaveDTO
     * @return
     */
    @PostMapping("/save")
    public RespBean foodSave(FoodSaveDTO foodSaveDTO) throws IOException {
        foodSaveDTO.setImg( Base64Utils.encodeToString(foodSaveDTO.getPic().getBytes()) );
        System.out.println(foodSaveDTO);
        Boolean yOn = foodService.saveFood(foodSaveDTO);
        if ( yOn ) {
            return RespBean.success("菜品信息已保存！", foodSaveDTO.getImg());
        }
        return RespBean.error("菜品名称已被使用！");
    }

    /**
     * 菜品删除
     * @param foodId
     * @return
     */
    @GetMapping("/delete")
    public RespBean foodDelete( @RequestParam("id") Integer foodId ) {
        foodService.foodDelete(foodId);
        return RespBean.success("菜品删除成功！");
    }

    /**
     * 清零计数器
     *  使用情景：
     *      1、已点列表重置
     *      2、用户确认下单
     * @return
     */
    @GetMapping("/clearNumber")
    public RespBean clearNumber() {
        foodService.clearNumber();
        return RespBean.success("清除成功！");
    }

    /**
     * 更新计数器
     * idAndOperation：id 和 加或减
     *      最后一位是0代表加
     *      最后一位是1代表减
     * @param idAndOperation
     * @return
     */
    @GetMapping("/updateNumber")
    public RespBean updateNumber( @RequestParam("idAndOperation") String idAndOperation) {

        int result = foodService.updateNumber(idAndOperation);
        if (result < 0) {
            return RespBean.error("更新失败！");
        }
        return RespBean.success("更新成功！", result);
    }


}
